import React, { useState, useEffect, useRef } from "react";
import { Card, Button, Table, message, Modal } from "antd";
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import {
  reqCategorys,
  reqAddCategory,
  reqUpdateCategory,
  reqDeleteCategory,
} from "../../api";
import AddUpdateForm from "./add-update-form";
const { confirm } = Modal;

const Category = () => {
  const [categorys, setCategorys] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalTitle, setModalTitle] = useState("添加分类");
  const [currentCategory, setCurrentCategory] = useState(null);
  const formRef = useRef(null);

  useEffect(() => {
    getCategorys(); // 在组件挂载时调用获取分类数据的函数
  }, []);

  const getCategorys = async () => {
    try {
      const res = await reqCategorys();
      console.log("Categorys response:", res); // 查看响应结果
      if (res.status === 0) {
        setCategorys(res.data);
      } else {
        message.error("获取分类列表失败了");
      }
    } catch (error) {
      console.error("获取分类列表失败:", error);
      message.error("获取分类列表失败了");
    }
  };

  const showModal = (title, category = null) => {
    setModalTitle(title);
    setCurrentCategory(category);
    setIsModalOpen(true);
  };
  const handleOk = async () => {
    try {
      const values = await formRef.current.validateFields();
      const { categoryName } = values;
      let result;
      if (modalTitle === "添加分类") {
        result = await reqAddCategory({ categoryName });
      } else {
        const categoryId = currentCategory._id;
        result = await reqUpdateCategory({ categoryId, categoryName });
      }
      formRef.current.resetFields();
      setIsModalOpen(false);
      if (result.status === 0) {
        message.success(`${modalTitle}成功`);
        getCategorys();
      } else {
        message.error(`${modalTitle}失败`);
      }
    } catch (error) {
      console.error(`${modalTitle}失败:`, error);
      message.error(`${modalTitle}失败`);
    }
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleDelete = (category) => {
    confirm({
      title: "确定删除这个分类吗?",
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const result = await reqDeleteCategory(category._id);
        if (result.status === 0) {
          message.success("删除分类成功");
          getCategorys();
        } else {
          message.error("删除分类失败");
        }
      },
    });
  };

  const extra = (
    <Button type="primary" onClick={() => showModal("添加分类")}>
      <PlusOutlined />
      添加
    </Button>
  );

  const columns = [
    {
      title: "分类的名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "操作",
      key: "action",
      width: 300,
      render: (record) => (
        <>
          <Button type="primary" onClick={() => showModal("修改分类", record)}>
            修改分类
          </Button>
          <Button
            type="default"
            style={{ marginLeft: 10 }}
            onClick={() => handleDelete(record)}
          >
            删除分类
          </Button>
        </>
      ),
    },
  ];

  return (
    <Card extra={extra}>
      <Table
        columns={columns}
        dataSource={categorys}
        rowKey="_id"
        bordered
        pagination={{ defaultPageSize: 2, showQuickJumper: true }}
      />
      <Modal
        title={modalTitle}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <AddUpdateForm
          categoryName={currentCategory ? currentCategory.name : ""}
          formRef={formRef}
        />
      </Modal>
    </Card>
  );
};

export default Category;
